﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using TSharp.Core.Repository;
using TSharp.Core.Repository.EntityFramework;
using TSharp.Core.Osgi;
using TSharp.Core.Util;
using System.Configuration;
using System.Data.Common;
[assembly: TSharp.Core.Osgi.RegLazyLoading(typeof(IUnitOfWorkFactory), typeof(EntityFrameworkUnitOfWorkFactory))]
namespace TSharp.Core.Repository.EntityFramework
{
    /// <summary>
    /// Unit of work factory implementation for Entity Framework.
    /// Note: implementation based on extension Feature CTP4.
    /// </summary>
    public class EntityFrameworkUnitOfWorkFactory : Disposable, IUnitOfWorkFactory
    {
        public EntityFrameworkUnitOfWorkFactory()
        {

        } 
      
        public IUnitOfWork BeginUnitOfWork(bool isReadonly, bool containDeleted)
        {
            return new EntityFrameworkUnitOfWork(ModelBuilderManager.CreateDbContext(), isReadonly, containDeleted);
        }
        public IUnitOfWork BeginUnitOfWork(bool isReadonly)
        {
            return BeginUnitOfWork(isReadonly, false);
        }
        public IUnitOfWork BeginUnitOfWork()
        {
            return BeginUnitOfWork(false);
        }


        public void EndUnitOfWork(IUnitOfWork unitOfWork)
        {
            ;
            if (unitOfWork != null)
            {
                (unitOfWork as EntityFrameworkUnitOfWork).Dispose(); 
            }
        }

        private bool disposed;
        protected override void Dispose(bool disposing)
        {
            if (!disposed)
            {
                try
                {
                    if (disposing)
                    {
                        // 释放托管资源
                    }
                    // 这里释放所有非托管资源
                    disposed = true;
                }
                finally
                {
                    base.Dispose(disposing);
                }
            }
        }

    }
}

